package com.atguigu.aiproject.service.impl;

import com.atguigu.aiproject.mapper.AdminMapper;
import com.atguigu.aiproject.mapper.UserMapper;
import com.atguigu.aiproject.entity.User;
import com.atguigu.aiproject.service.AdminService;
import com.atguigu.aiproject.utils.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    private static final Logger log = LoggerFactory.getLogger(AdminServiceImpl.class);
    public final String USER_ROLE_KEY = "user:role:";
    private final AdminMapper adminMapper;
    private final UserMapper userMapper;
    private final RedisTemplate<String, Object> redisTemplate;


    public AdminServiceImpl(AdminMapper adminMapper, UserMapper userMapper, RedisTemplate<String, Object> redisTemplate) {
        this.adminMapper = adminMapper;
        this.userMapper = userMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void executeSql(String sql) {
        // TODO 拦截除insert、update、delete之外的SQL，并只允许对规定的表进行操作
        adminMapper.executeSql(sql);
    }

    @Override
    public List<Map<String, Object>> selectSql(String sql) {
        // TODO 拦截除select之外的SQL，并只允许查询规定的表
        return adminMapper.selectSql(sql);
    }

    public boolean isAdmin() {
        int userId = UserContext.getUserId();
        final String userRoleKey = USER_ROLE_KEY + userId;
        try {
            Integer role = (Integer) redisTemplate.opsForValue().get(userRoleKey);
            if (role != null && role == 1) {
                return true;
            }
        } catch (Exception e) {
            log.warn("从redis获取用户身份失败");
        }

        int role = adminMapper.getUserRoleById(userId);
        try {
            redisTemplate.opsForValue().set(userRoleKey, role);
        } catch (Exception e) {
            log.warn("保存用户身份到redis失败");
        }
        return role == 1;
    }

    @Override
    public Page<User> getUsers(int pageNum, int pageSize) {
        // 创建分页对象
        Page<User> userPage = new Page<>(pageNum, pageSize);
        // 创建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 根据用户ID排序，假设是升序排列
        queryWrapper.orderByAsc("id");
        // 执行分页查询
        // 返回结果
        // TODO redis
        return userMapper.selectPage(userPage, queryWrapper);
    }

    @Override
    public List<User> getUsersByIds(List<Integer> userIds) {
        return adminMapper.getUsersByIds(userIds);
    }
}
